// tips: 因该功能包含大量异步操作，使用时，其所在函数须为async
/*

用法示例:
try {
	const scopeStatus = await this.$checkScope('scope.writePhotosAlbum');
	if (!scopeStatus) return void 0;
} catch (e) {
	return void 0;
}

...这里可以正常写业务逻辑...
*/

/* scope集合*/
const scopeList = [{
		scope: 'scope.userInfo',
		name: '用户信息'
	},
	{
		scope: 'scope.userLocation',
		name: '地理位置'
	},
	{
		scope: 'scope.userLocationBackground',
		name: '后台定位'
	},
	{
		scope: 'scope.address',
		name: '通信地址'
	},
	{
		scope: 'scope.record',
		name: '录音功能'
	},
	{
		scope: 'scope.writePhotosAlbum',
		name: '保存到相册'
	},
	{
		scope: 'scope.camera',
		name: '摄像头'
	},
	{
		scope: 'scope.invoice',
		name: '获取发票'
	},
	{
		scope: 'scope.invoiceTitle',
		name: '发票抬头'
	},
	{
		scope: 'scope.werun',
		name: '微信运动步数'
	}
];

const scopeFn = {
	/**
	 * 限频接口，需要缓存
	 * 参考链接：https://developers.weixin.qq.com/miniprogram/dev/framework/performance/api-frequency.html
	 */
	_getScope(scopeName = '', force = false) {

		return new Promise((resolve, reject) => {
			try {
				const _self = scopeFn;
				if (getApp().globalData._cacheScope[scopeName.toString()] && !force) {
					resolve(getApp().globalData._cacheScope);
					return;
				};
				uni.getSetting({
					success(res) {
						getApp().globalData._cacheScope = res.authSetting;
						resolve(getApp().globalData._cacheScope);
					},
					fail(res) {
						console.error(`获取用户权限信息异常：`);
						console.error(res);
						reject(res);
					}
				});
			} catch (e) {
				console.log(e);
			}
		});
	},
	_setScope() {
		return new Promise((resolve, reject) => {
			const _self = scopeFn;
			uni.openSetting({
				success(res) {
					getApp().globalData._cacheScope = res;
					const {
						authSetting
					} = getApp().globalData._cacheScope;

					resolve(authSetting);
				},
				fail(err) {
					console.error('返回用户设置的操作结果异常：');
					console.log(err);
					reject(err);
				},
				complete(res) {
					console.log('设置页已关闭');
				}
			});
		});
	},
	_setAuthorize(scope) {
		const _self = scopeFn;
		return new Promise((resolve, reject) => {
			uni.authorize({
				scope: scope,
				success() {
					resolve(true);
				},
				fail() {
					reject(false);
				}
			});
		});
	},
	setModal(scope) {
		const _self = scopeFn;
		return new Promise((resolve, reject) => {
			uni.showModal({
				showCancel: false,
				confirmText: '确定',
				content: `请在设置页打开${scope}权限`,
				success: function(res) {
					if (res.confirm) {
						resolve(true);
					} else {
						reject(false);
					}
				},
				fail: function(res) {
					reject(false);
				}
			});
		});
	},
	async checkScope(scopeName, {
		force = false
	} = {}) {

		const _self = scopeFn;

		let targetScope = scopeList.filter(item => {
			return item.scope === scopeName;
		});

		if (targetScope.length) {
			targetScope = targetScope[0];
		} else {
			throw new Error('请输入正确的scope name');
			return false;
		}

		let getScope, setAuthorize, openSetting;
		// 查询用户权限
		try {
			getScope = await _self._getScope(scopeName, force);
		} catch (e) {
			console.error(`查询用户权限失败1：${JSON.stringify(e)}`);
			_self.scopeError(e);
			return false;
		}

		if (getScope[scopeName] === undefined) {
			//没有获取过该权限
			try {
				setAuthorize = await _self._setAuthorize(scopeName);
			} catch (e) {
				//用户拒绝了该权限
				return false;
			}
			// 记录成功授权的状态
			getApp().globalData._cacheScope[scopeName] = true;
			return true;
		} else if (getScope[scopeName] === false) {
			//拒绝过该权限
			try {
				const modalStatus = await _self.setModal(targetScope.name);
			} catch (e) {
				console.error(`查询用户权限失败2：${JSON.stringify(e)}`);
				_self.scopeError(e);
				return false;
			}

			try {
				openSetting = await _self._setScope();
			} catch (e) {
				console.error(`查询用户权限失败3：${JSON.stringify(e)}`);
				_self.scopeError(e);
				return false;
			}
			getApp().globalData._cacheScope[scopeName] = openSetting[scopeName] === true ? true : false;
			return getApp().globalData._cacheScope[scopeName];
		} else {
			//成功授权过该权限
			return true;
		}
	},
	scopeError() {
		uni.showModal({
			showCancel: false,
			confirmText: '确定',
			title: '获取权限失败，请在设置页手动打开该权限',
			complete: function(res) {}
		});
	},
}


export default scopeFn['checkScope']
